package com.zfp.sslserver;

import io.grpc.*;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.NettyServerBuilder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.File;
import java.io.IOException;

@SpringBootApplication
public class Application {

    public static void main(String args[]) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

        grpcStarter(context);
    }

    private static void grpcStarter(ConfigurableApplicationContext applicationContext) {

        ServerBuilder serverBuilder;
        try {
            File certFile = new File("/home/zfp/demo/ssl-server-demo/src/main/resources/ssl/grpc_ca/gserver.cer");
            File keyFile = new File("/home/zfp/demo/ssl-server-demo/src/main/resources/ssl/grpc_ca/gserver.key");

            // Failed to load any of the given libraries: [netty-tcnative-linux-x86_64, netty-tcnative-linux-x86_64-fedora, netty-tcnative]
            SslContext sslContexts = GrpcSslContexts.configure(SslContextBuilder.forServer(certFile, keyFile).sslProvider(SslProvider.OPENSSL), SslProvider.OPENSSL).build();

            serverBuilder = NettyServerBuilder.forPort(9999)
                    .sslContext(sslContexts);
            Object service = applicationContext.getBean("SslTestGrpcController");

            serverBuilder.addService(BindableService.class.cast(service).bindService());

            serverBuilder.build().start();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}